package com.zyx.xml.dom;

import javax.xml.parsers.*;
import java.io.*;

import cn.hutool.core.io.resource.ClassPathResource;
import org.xml.sax.*;

/**
 * Description:
 * <br/>10.2.4 使用DTD验证XML文档
 *
 * @author Yaxi.Zhang
 * @since 2022/9/25 08:31
 */
public class DTDValidateWithHandler {
    public static void main(String[] args) throws Exception {
        // DOM解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 设置使用DTD验证XML文档
        factory.setValidating(true);
        // 获取DOM解析器
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 为解析器绑定ErrorHandler
        builder.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException exception) throws SAXException {
                System.out.println("---error方法---");
                System.out.println(exception.getSystemId() + "文档的第"
                        + exception.getLineNumber()
                        + "行，第" + exception.getColumnNumber()
                        + "发生有效性错误，错误信息是：" + exception.getMessage());
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                System.out.println("---fatalError方法---");

            }

            public void warning(SAXParseException exception) throws SAXException {
                System.out.println("---warning方法---");
            }
        });
        //开始解析XML文档
        builder.parse(new ClassPathResource("ch10_02/book.xml").getFile());
    }
}
